﻿using SuddenDeath.Domain.Services.FileManager.elFinder.Responses;
using SuddenDeath.Domain.Services.FileManager.elFinder.Utils;

namespace SuddenDeath.Domain.Services.FileManager.elFinder.Commands
{
    public class Duplicate : ICommand
    {
        public string Target { get; set; }

        public string Current { get; set; }

        public Duplicate(string current, string target)
        {
            Target = target;
            Current = current;            
        }

        #region ICommand Members       

        public Response Execute()
        {
            var path = DirectoryUtils.GetRelativePathByHash(Current, Configuration.Configuration.RootPath);

            var toDuplicate = DirectoryUtils.GetFilePathByHash(Target, Configuration.Configuration.RootPath);

            var isDir = false;

            string newName;

            try
            {
                var fileInfo = new System.IO.FileInfo(toDuplicate);
                newName = fileInfo.Duplicate();
                newName = newName.Hash();                
            }
            catch
            {
                var dirInfo = new System.IO.DirectoryInfo(toDuplicate);
                newName = dirInfo.Duplicate();
                newName = newName.Hash();
                isDir = true;
            }

            var folder = new Folder(path);

            var response = new ActionCompletedResponse
                               {
                                   cwd = folder.Cwd,
                                   cdc = folder.Contents,
                                   Select = new[] {newName}
                               };

            if (isDir)
            {
                response.tree = folder.Tree;
            }

            return response;
        }

        #endregion
    }
}
